<?php
namespace Home\Controller;
use Think\Controller;
/**
 * 供应商商品管理控制器
 * @author blakefan <162174394@qq.com>
 * 
 */

class ItemController extends HomeController{
	/**
	 * 商品列表
	 */
	public function index(){

		$item=D('Item');
	 	$result=$item->index();
		$this->assign('items',$result['item']);
		$this->assign('pagearr',$result['pagearr']);
		$this->display('index');	

	}

	/**
	 * 查看商品详情
	 */
	public function getItem(){
		$itemid=I('get.itemid','','strip_tags');
      if(!$itemid) return false;
      //获取分类树
	  $typearr=$this->getListCat();
      //获取商品基本信息
      $item=M('item');
      $iteminfo=$item->where('itemid=%d',$itemid)->select();
      //获取该类目下的所有属性
		$typeproperty=M('type a')->join('inner join '. C('DB_PREFIX').'type_property b on a.typeid=b.typeid ')
		          ->where('a.typeid=%d',$iteminfo[0]['typeid'])
		          ->getField('b.propertyid,a.typeid,a.typename,b.propertyname');
		  if(!empty($typeproperty))
		  {
		  	foreach($typeproperty as $key=>&$value)
		  	{
		 	$where['propertyid']=$key;
		 	$value['select']=M('type_property a')->join('inner join '.C('DB_PREFIX').'type_propertyvalue b on a.propertyid=b.propertyid')
		 		             ->where('a.propertyid=%d',$where['propertyid'])
		 		             ->getField('b.valueid,a.propertyid,a.propertyname,b.propertyvalue ');
		 	}

		  }  
		//获取已选择的属性
		$seledpro=M('item_property')->where('itemid=%d',$iteminfo[0]['itemid'])->getField('propertyid,propertyvalueid');
		 foreach($typeproperty as $key=>&$value)
		 {
             
		 	foreach($value['select'] as $k=>&$v)
		 	{
		 		
		 		if($v['valueid']==$seledpro[$key])
		 		{

		 			$v['selected']='true';
		 		}
		 	}
		 }
		//获取该类目下所有品牌
		 $brands=M('type_brand a ')->join('inner join '.C('DB_PREFIX').'brand b on a.brandid= b.brandid')
		         ->where('b.isdel=0 AND a.typeid='.$iteminfo[0]['typeid'])
		         ->getField('b.brandid,b.brandname');
		 
		 //获取该类目下所有规格
		 $spec_type=M('type_spec a ')->join('inner join '.C('DB_PREFIX').'spec b  on a.specid =b.specid ')
		  			->where('a.typeid=%d',$iteminfo[0]['typeid'])->getField('a.specid,a.typeid,b.`name`');
		 if(!empty($spec_type))
		 {
		 	foreach($spec_type as $key=>&$value)
		 	{
		 			$where['specid']=$key;
		 			$value['specval']=M('specval')->where('specid=%d',$where['specid'])->getField('specvalid,specid,name');
		 	}
		 }
		 //该产品选中的规格
		 $serspec=M('item_spec')->where('itemid=%d',$itemid)->getField('specid,self');
		 foreach($serspec as $k=>&$v){
		 	$v=unserialize($v);
		 }
		 foreach($spec_type as $key=>&$value){
		 	foreach($value['specval'] as $k=>&$v){
		 		foreach($serspec[$key] as $i=>$sname)
		 		 {
		 		 	if($i==$v['specvalid']){
		 		 		$v['checked']='true';
		 		 	}
		 		}
		 		
		 	}
		 }
		//判断此商品是否为货品(即不同规格对应不同价格和库存)
	  $products=M('product')->where('itemid=%d',$itemid)->getField('productid,itemid,inventory,price');
	  if($products){
         $productspecs=M('product_spec')->where('itemid=%d',$itemid)->select(); 
         foreach($productspecs  as $spec){
         		$products[$spec["productid"]]["specs"][$spec["specid"]] =$spec["specvalid"];
         }  
	  }
	  //获取商品详情
	  $detail=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');
	  $this->assign('detail',$detail);
	  $this->assign('typearr',$typearr);
	  $this->assign('products',$products);
 	  $this->assign('iteminfo',$iteminfo[0]);
	  $this->assign('brands',$brands);
	  $this->assign('typeproperty',$typeproperty);
	  $this->assign('specs',$spec_type);
	  
      $this->display('getitem');
	}

	/**
	 *
	 * 返回已经确定子分类的类别属性，计算等级
	 *
	 */
	public function getListCat($data = array(),$level = 0) {
		$cats = array();
		!$data && $data = $this->getCats();
		if(!$data) return $cats;
		foreach($data as $key => $val) {
			$cats[$val['typeid']] = &$data[$key];
			$cats[$val['typeid']]['level'] = $level;
			if( isset( $val['children'] ) ) {
				$cats[$val['typeid']]['haschild'] = 1;
				$cats += $this->getListCat($val['children'],$level + 1);
				unset($data[$key]['children']);
			} 
		}
		return $cats;
	}
	
	/**
	 *
	 * 获取所有类别
	 *
	 */
	protected function getCats($return = 'tree') {
		static $retarr;
		if(isset($retarr[$return])) return $retarr[$return];

		$cats = M('type')->getField('typeid,typename,pid');
		if($return == 'tree')
		{			//返回数组
			$tree = array();

			foreach($cats as $cat)
			 {	//循环cat
				if(isset($cats[$cat['pid']])) 
				{//非第一级
					$cats[$cat['pid']]['children'][] = &$cats[$cat['typeid']];
				} else
				 {//第一级
					$tree[] = &$cats[$cat['typeid']];

				}
			}
			$retarr[$return] = $tree;
		} else if($return == 'source')
		 {//返回source
			$retarr[$return] = $cats;
		}
		return $retarr[$return];
	}
	/*
     *ajax 弹出货品规格（颜色，价格，库存，供应价）
     *@param itemid
     *@return json
    */
      public function ajaxProduct(){
        $itemid=I('post.itemid',0,'strip_tags');
        $item=M('item a');
        $products=$item->join('inner join '.C('DB_PREFIX').'product b on a.itemid=b.itemid')
        			   ->where('a.itemid=%d',$itemid)
        			   ->getField('b.productid,a.itemid,a.itemname,a.bn,b.price,b.color,b.supprice,b.inventory');
        $result=array();
        $result['status']=!empty($products)?1:0;
        $result['message']=empty($products)?'此产品没有规格':'';
        $result['products']=!empty($products)?array_values($products):'';

        echo json_encode($result);
    }

	/**
	 * 商品预览
	 */
	 public function viewItem()
    {
        $itemid=I('get.itemid',0,'strip_tags');
        $result=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');
        $this->assign('itemdesc',$result);
        $this->display('preview');
    }

    	/*
	  *ajax 修改价格，供货价，库存
	  *@param itemid
	  *@param action
	  *@param value
	  *return json
	  */
	 public function ajaxEditItem()
	 {
	 	
	 	$action=I('post.action',0,'strip_tags');
	 	$itemid=I('post.itemid',0,'strip_tags');
	 	$spanval=I('post.spanval',0,'strip_tags');
	 	$spanval=intval($spanval);
	 	$where['itemid']=array('eq',intval($itemid)); 
	 	$item=M('item');
	 	
	 	$result=array();
	 	$status=false;
	 	switch ($action) 
	 	{
	 		//修改售价
	 		case 'price':
	 			if (empty($itemid)) break;
	 			$oldsupprice=$item->where("itemid=%d",$itemid)->getField('supperprice');
	 			if ($spanval < $oldsupprice ) {
	 				$result['status']=0;
			 		$result['msg']='零售价必须大于供货价';
			 		echo json_encode($result,JSON_UNESCAPED_UNICODE);
			 		return '';
	 			}
	 			
	 			$item->price=$spanval;
	 			$status=$item->where($where)->save();
	 			break;
	 		
	 		case 'supprice':
	 		if (empty($itemid)) break;
	 			$where['supperprice']=array('egt',0);
	 			$item->supperprice=$spanval;
	 			$status=$item->where($where)->save();
	 			if ($status === 0) 
			 	{
			 		$result['status']=0;
			 		$result['msg']='供货价必须大于0';
			 		echo json_encode($result,JSON_UNESCAPED_UNICODE);
			 		return '';

			 	}
	 			break;
	 		case 'inventory':
	 			if (empty($itemid)) break;
	 			$where['inventory']=array('egt',0);
	 			$item->inventory=$spanval;
	 			$status=$item->where($where)->save();  
	 			if ($status === 0) 
			 	{
			 		$result['status']=0;
			 		$result['msg']='库存必须大于0';
			 		echo json_encode($result,JSON_UNESCAPED_UNICODE);
			 		return '';

			 	}
	 			break;
	 	}
	 	if ($status !== false) 
	 	{
	 		$result['status']=1;
	 		//修改成功之后，将产品状态改为未审核，需总后台审核
	 		$item=M('item');
	 		$item->create();
	 		$item->examine=0;
	 		$item->status =2;
	 		$item-> where('itemid=%d',$itemid)->save();
	 		echo json_encode($result,JSON_UNESCAPED_UNICODE);
	 		return '';

	 	}
	 	$result['status']=0;
	 	$result['msg']='系统繁忙，请稍后再试！';
	 	echo json_encode($result,JSON_UNESCAPED_UNICODE);
	 	return '';
	 }
	  /*
     ×ajax 直接修改货品价格，颜色，库存，供应价
     @param productid
     return json
     */
     public function ajaxEditproduct()
     {
        $result=array();
        $action=I('post.action','','strip_tags');
        $productid=I('post.productid',0,'strip_tags');
        $itemid=I('post.itemid',0,'strip_tags');
        $value=I('post.spanval','','strip_tags');
        if(empty($action) || empty($productid) )
        { 
            $result['status']=0;
            $result['message']='系统繁忙，请稍后再试！';
            echo json_encode($result);
            return '';
        }
        $product=M('product');
        $where['productid']=$productid;
        switch ($action) 
        {
            case 'prodcutcolor':
                //修改货品颜色
            $data['color']=$value;
            $temp=$product->where($where)->save($data);
            break;
            case 'prodcutprice':
                //修改货品价格
            $data['price']=$value;
            $temp=$product->where($where)->save($data);
            break;
            case 'prodcutsupprice':
                //修改货品供应价
            $data['supprice']=$value;
            $temp=$product->where($where)->save($data);
            break;
            case 'productinventory':
                //修改库存
            $data['inventory']=$value;
            $temp=$product->where($where)->save($data);
            break;
        }
        if (!empty($itemid))
        {
            //获取货品的库存和，更新基础库存
            $suminven =$product->where('itemid=%d',$itemid)->sum('inventory');

            $suminven=intval($suminven);
            $res=M('item')->where('itemid=%d',$itemid)->save(array('inventory'=>$suminven));
            if ($res !== false)
            {
                $result['itemid']=$itemid;
                $result['suminven']=$suminven;      
            }   
        }
        if($temp !==false)
        {
            //修改成功后需要将商品修改为下架状态和未审核
            $item=M('item');
	 		$item->create();
	 		$item->examine=0;
	 		$item->status =2;
	 		$item-> where('itemid=%d',$itemid)->save();
            $result['status']=1;
            echo json_encode($result);
            return '';
        }
        $result['status']=0;
        echo json_encode($result);
        return '';
        
    }
	

}